package com.kun.service_edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kun.service_edu.entity.EduSubject;
import com.kun.service_edu.entity.excel.SubjectData;
import com.kun.service_edu.entity.subject.OneSubject;
import com.kun.service_edu.entity.subject.TwoSubject;
import com.kun.service_edu.listener.SubjectExcelListener;
import com.kun.service_edu.mapper.EduSubjectMapper;
import com.kun.service_edu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-10-02
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
       try {
           InputStream fileInputStream = file.getInputStream();
           EasyExcel.read(fileInputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
       }catch (Exception e){
            e.printStackTrace();
       }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        //查询所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubgect = baseMapper.selectList(wrapperOne);
        //查询所有二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubgect = baseMapper.selectList(wrapperTwo);
        //封装一级分类
        List<OneSubject> list =new ArrayList<>();
        for (int i= 0;i<oneSubgect.size();i++){
            EduSubject eduSubject = oneSubgect.get(i);
            //把eduSubject里面的值取出来，放到oneSubgect中
            OneSubject oneSubject = new OneSubject();
//            oneSubject.setId(eduSubject.getId());
//            oneSubject.setTitle(eduSubject.getTitle());

            BeanUtils.copyProperties(eduSubject,oneSubject);
            list.add(oneSubject);
            List<TwoSubject> twoSubjectList = new ArrayList<>();
            for (int m=0;m<twoSubgect.size();m++){
                EduSubject tSubject= twoSubgect.get(m);
                if (tSubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubject);
                    twoSubjectList.add(twoSubject);
                }

            }

            oneSubject.setChildren(twoSubjectList);
        }





        return list;
    }
}
